package com.right.health.app.ui.registered;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.magic.basic.utils.CollectionUtil;
import com.magic.basic.utils.ScreenUtil;
import com.magics.http.listener.OnHttpListener;
import com.magics.http.model.Request;
import com.magics.http.model.Response;
import com.right.health.app.R;
import com.right.health.app.app.App;
import com.right.health.app.base.BasePresenterActivity;
import com.right.health.app.bean.AppUserResponse;
import com.right.health.app.bean.ManBingInfo;
import com.right.health.app.bean.PayClinicOrderBean;
import com.right.health.app.bean.PayInfo;
import com.right.health.app.constants.BroadCastCode;
import com.right.health.app.db.DaoSharedPreferences;
import com.right.health.app.net.OrderApi;
import com.right.health.app.net.UserApi;
import com.right.health.app.ui.me.SocialSecurityInfoActivity;
import com.right.health.app.widget.NumberEditText;
import com.vendor.social.PayApi;
import com.vendor.social.model.PayType;
import com.vendor.social.pay.WxPay;
import com.vendor.social.utils.ToastUtil;

import org.json.JSONObject;

import java.util.List;

/**
 * 诊间支付订单确认
 */
public class PayClinicOrderActivity extends BasePresenterActivity implements View.OnClickListener, OnHttpListener, PayApi.OnPayListener {
    public static final String ORDER_ID_KEY = "orderId";
    private static final int REQUEST_ORDER_CODE = 532;
    private static final int REQUEST_PAY_CODE = 433;
    private static final int REQUEST_SOCIAL_PARAM_CODE = 434;
    private static final int HTTP_CODE_GET_USER_INFO = 1;
    public static final int PAY_TYPE_WX = 10;
    public static final int PAY_TYPE_ALI_PAY = 11;
    public static final int PAY_TYPE_SOCIAL = 12;

    private String mOrderId;
    private TextView mHosTv, mPatientTv, mPatientIdTv, mCostTv, mBalanceTv,mBindSocialTv,mBindHosTv,mDiseaseTv;
    private RelativeLayout mBindHosRL,mDiseaseRL;
    private LinearLayout mCostItemLL;
    private View[] mPayItems;
    private ImageView[] mPaySelectedImage;
    private Button mPayBtn;
    private OrderApi mOrderApi;
    private UserApi mUserApi;
    private boolean mBindSocial;
    private int mHosSelIndex;
    private String[] mHosStr;
    private PayClinicOrderBean mOrderBean;
    private List<ManBingInfo> mManBingInfo;
    private AppUserResponse.AppUserInfo mUserInfo;
    private int mPayType = -1;
    private boolean mIsVerify;

    public static void launch(Context context, String orderId) {
        Bundle bundle = new Bundle();
        bundle.putString(ORDER_ID_KEY, orderId);
        Intent intent = new Intent(context, PayClinicOrderActivity.class);
        intent.putExtras(bundle);
        context.startActivity(intent);
    }

    @Override
    public void onCreate(Bundle bundle, String s) {
        setContentView(R.layout.activity_pay_clinic_order);
    }

    @Override
    public void findView() {
        mHosTv = findViewById(R.id.tv_hospital);
        mPatientTv = findViewById(R.id.tv_patient);
        mPatientIdTv = findViewById(R.id.tv_patient_id);
        mCostTv = findViewById(R.id.tv_money);
        mCostItemLL = findViewById(R.id.ll_cost_item);
        mPayBtn = findViewById(R.id.btn_sure);
        mBalanceTv = findViewById(R.id.tv_social_balance);
        mBindSocialTv = findViewById(R.id.tv_bind_social_security);
        mBindHosTv=findViewById(R.id.tv_bind_hospital);
        mDiseaseTv = findViewById(R.id.tv_disease);
        mBindHosRL=  findViewById(R.id.ly_bind_hospital);
        mDiseaseRL=findViewById(R.id.ly_disease);
        mBindSocialTv.setOnClickListener(this);
        mPayItems = new View[3];
        mPayItems[0] = findViewById(R.id.rl_pay_alipay_item);
        mPayItems[0].setTag(PAY_TYPE_ALI_PAY);
        mPayItems[0].setVisibility(View.GONE);
        mPayItems[1] = findViewById(R.id.rl_pay_wechat_item);
        mPayItems[1].setTag(PAY_TYPE_WX);
        mPayItems[2] = findViewById(R.id.rl_pay_social_security_item);
        mPayItems[2].setTag(PAY_TYPE_SOCIAL);
        mPaySelectedImage = new ImageView[3];
        mPaySelectedImage[0] = findViewById(R.id.iv_selected_alipay);
        mPaySelectedImage[1] = findViewById(R.id.iv_selected_wechat);
        mPaySelectedImage[2] = findViewById(R.id.iv_selected_social);
        mPayBtn.setOnClickListener(this);
//        mDiseaseRL.setOnClickListener(this);
        mBindHosRL.setOnClickListener(this);
        for (View view : mPayItems) {
            view.setOnClickListener(this);
        }
    }

    @Override
    public void initialize() {
        if (getIntent().getExtras() != null) {
            mOrderId = getIntent().getExtras().getString(ORDER_ID_KEY);
        }
        if (TextUtils.isEmpty(mOrderId)) {
            ToastUtil.show(this, "订单不存在");
            finish();
        } else {
            mOrderApi = new OrderApi();
            mOrderApi.setListener(this);
            mOrderApi.addRequestCode(REQUEST_ORDER_CODE);
            mOrderApi.getPayClinicOrder(mOrderId);
            mUserApi = new UserApi();
            mUserApi.setListener(this);

            mUserApi.addRequestCode(HTTP_CODE_GET_USER_INFO);
            mUserApi.getUserInfo();
        }
        mUserInfo = App.getInstance().getUser();
        if (mUserInfo != null) {
            dealSocialSecurity();
        }
        mManBingInfo = DaoSharedPreferences.getInstance().getManBingInfo();
        if (!CollectionUtil.isEmpty(mManBingInfo)) {
            mDiseaseRL.setVisibility(View.VISIBLE);
            mBindHosRL.setVisibility(View.VISIBLE);
            findViewById(R.id.view_split);
            mBindHosTv.setText(mManBingInfo.get(0).mbHospital);
            mDiseaseTv.setText(mManBingInfo.get(0).mbName);
            mHosSelIndex=0;
            mHosStr = new String[mManBingInfo.size()];
            for (int i=0;i<mManBingInfo.size();i++) {
                mHosStr[i]=mManBingInfo.get(i).mbHospital;
            }
        }
    }

    private void dealSocialSecurity() {
        mIsVerify = mUserInfo.isVertificationSucc();
        if (mUserInfo.isManbing == 1) {
            mPayItems[2].setVisibility(View.VISIBLE);
            mBalanceTv.setText(String.valueOf(mUserInfo.balance));

        } else {
            mPayItems[2].setVisibility(View.GONE);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_pay_alipay_item:
            case R.id.rl_pay_wechat_item:
            case R.id.rl_pay_social_security_item:
                mPayType = (int) v.getTag();
                for (int i = 0; i < mPayItems.length; i++) {
                    if (mPayItems[i] == v) {
                        mPayItems[i].setSelected(true);
                    /*    if (mPaySelectedImage[i] != null) {
                            mPaySelectedImage[i].setVisibility(View.VISIBLE);
                        }*/

                    } else {
                        mPayItems[i].setSelected(false);
                     /*   if (mPaySelectedImage[i] != null) {
                            mPaySelectedImage[i].setVisibility(View.INVISIBLE);
                        }*/
                    }
                }
                break;
            case R.id.tv_bind_social_security:
                startIntent(SocialSecurityInfoActivity.class);
                break;
            case R.id.ly_bind_hospital:
                showHosSelectDialog();
                break;
            case R.id.btn_sure:
                if (!mIsVerify) {
                    Toast.makeText(this, "请先实名认证", Toast.LENGTH_SHORT).show();
                    return;
                } else if (mPayType == -1) {
                    Toast.makeText(this, "请选择支付方式", Toast.LENGTH_SHORT).show();
                    return;
                }
                try {
                    if (mPayType == PAY_TYPE_SOCIAL) {
                        if (mUserInfo.balance < Double.valueOf(mOrderBean.getPayamout())) {
                            Toast.makeText(this, "余额不足", Toast.LENGTH_SHORT).show();
                        } else {
//                            showPayDialog();
                            mProgressDialog = ProgressDialog.show(PayClinicOrderActivity.this, "", "支付中...");
                            mOrderApi.addRequestCode(REQUEST_SOCIAL_PARAM_CODE);
                            mOrderApi.getSocialParam(mOrderId ,mManBingInfo.get(mHosSelIndex).mbType);
                        }
                    } else {
                        mOrderApi.setTag(mPayType);
                        mOrderApi.addRequestCode(REQUEST_PAY_CODE);
                        mProgressDialog = ProgressDialog.show(PayClinicOrderActivity.this, "", "支付中...");
                        mOrderApi.payClinic(mOrderId, "",mPayType + "");
                    }
                } catch (Exception e) {
                    Toast.makeText(this, "未知异常", Toast.LENGTH_SHORT).show();
                }
        }
    }

    private void showHosSelectDialog() {
        if (mHosStr!=null) {
            AlertDialog.Builder items = new AlertDialog.Builder(this);
            items.setTitle("医院选择");
            items.setItems(mHosStr, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (which != mHosSelIndex) {
                        mHosSelIndex=which;
                        mBindHosTv.setText(mHosStr[which]);
                        mDiseaseTv.setText(mManBingInfo.get(which).mbName);
                    }
                }
            });
            items.create().show();
        }
    }

    private ProgressDialog mProgressDialog;

    private void showPayDialog() {
        Dialog dialog = new Dialog(this, R.style.dialog);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_pay_edit, null);
        dialog.setContentView(view);
        ImageView cancelIv = view.findViewById(R.id.iv_cancel);
        cancelIv.setOnClickListener((v -> dialog.cancel()));
        NumberEditText numberEditText = view.findViewById(R.id.et_password);
        numberEditText.setOnInputFinish((text -> {
            mOrderApi.setTag(PAY_TYPE_SOCIAL);
            mOrderApi.addRequestCode(REQUEST_PAY_CODE);
            mOrderApi.payClinic(mOrderId, text,PAY_TYPE_SOCIAL + "");
            dialog.dismiss();
            mProgressDialog = ProgressDialog.show(PayClinicOrderActivity.this, "", "加载中...");
        }));
        dialog.show();
        WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
        params.height = WindowManager.LayoutParams.WRAP_CONTENT;
        params.width = (int) (ScreenUtil.getInstance(this).getScreenWidth() * 0.85f);
        dialog.getWindow().setAttributes(params);
        new Handler().postDelayed(() -> {
            numberEditText.invisibleEt.requestFocus();
            InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            inputManager.showSoftInput(numberEditText.invisibleEt, 0);

        }, 100);
    }

    private void refreshUI() {
        mHosTv.setText("攀大附院");
        mPatientTv.setText(mOrderBean.getMembername());
        mCostTv.setText(mOrderBean.getPayamout() + "元");
        mPatientIdTv.setText(mOrderBean.getMemberid());
        if (!CollectionUtil.isEmpty(mOrderBean.getDetails())) {
            View line = new View(this);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, getResources().getDimensionPixelSize(R.dimen.dp_0_5));
            params.leftMargin = getResources().getDimensionPixelOffset(R.dimen.dp_16);
            params.rightMargin = getResources().getDimensionPixelOffset(R.dimen.dp_16);
            line.setBackgroundColor(getResources().getColor(R.color.color_EDEDED));
            for (int i = 0; i < mOrderBean.getDetails().size(); i++) {
                View layout = LayoutInflater.from(this).inflate(R.layout.layout_common_item, null);
                TextView drugTv = layout.findViewById(R.id.tv_left);
                TextView priceTv = layout.findViewById(R.id.tv_right);
                drugTv.setText(mOrderBean.getDetails().get(i).getItemname());
                if (!TextUtils.isEmpty(mOrderBean.getDetails().get(i).getItemprice())) {
                    priceTv.setText("￥" + mOrderBean.getDetails().get(i).getItemprice());
                }
                mCostItemLL.addView(layout);
                if (i < mOrderBean.getDetails().size() - 1) {
                    mCostItemLL.addView(line, params);
                }
            }
        }

    }

    @Override
    public void onResponse(Request request, Response response) {
        if (mProgressDialog!=null&&mProgressDialog.isShowing()){
            mProgressDialog.dismiss();
        }
        if (!response.isResponseFail()) {
            try {
                if (request.requestCode == HTTP_CODE_GET_USER_INFO) {
                    AppUserResponse appUserResponse = response.cast(AppUserResponse.class);
                    App.getInstance().refreshUser(appUserResponse.user);
                    mUserInfo = appUserResponse.user;
                    dealSocialSecurity();
                } else if (request.requestCode == REQUEST_ORDER_CODE) {
                    JSONObject jsonObject = new JSONObject(response.data);
                    if (!TextUtils.isEmpty(jsonObject.optString("unpaiddetail"))) {
                        mOrderBean = new Gson().fromJson(jsonObject.optString("unpaiddetail"), PayClinicOrderBean.class);
                        refreshUI();
                    }

                } else if (request.requestCode == REQUEST_PAY_CODE) {
                    if (mProgressDialog != null) {
                        mProgressDialog.dismiss();
                    }
                    PayInfo payInfo = response.cast(PayInfo.class);
                    int payType = (int) request.tag;
                    if (payType == PAY_TYPE_ALI_PAY) {
                        PayApi.pay(this, PayType.ALIPAY, payInfo.orderstr, this);
                    } else if (payType == PAY_TYPE_WX) {
                        WxPay wxPay = new WxPay(this);
                        wxPay.setOnPayListener(this);
                        wxPay.pay(payInfo.wxdata);
                    } else if (payType == PAY_TYPE_SOCIAL) {
                        onPayOk();
                    }
                }else if (request.requestCode==REQUEST_SOCIAL_PARAM_CODE){
                    if (!TextUtils.isEmpty(response.data)){
                        JSONObject jsonObject = new JSONObject(response.data);
                        String param = jsonObject.optString("data");
                        String url="panzhihuasociety://medicalpay?"+param;
                        Log.i("TAG", "onResponse: "+url);

                        Intent intent = new Intent();
                        intent.setAction(Intent.ACTION_VIEW);
                        intent.setData(Uri.parse(url));
                        if (getPackageManager().resolveActivity(intent, 0) != null) {
                            this.startActivity(intent);
                        }else {
                            Toast.makeText(this, "未安装医保应用，请安装后再试!", Toast.LENGTH_SHORT).show();
                        }

                    }else {
                        Toast.makeText(this, "确认订单失败", Toast.LENGTH_SHORT).show();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        } else {
            Toast.makeText(this, response.error, Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onPayOk() {
        ToastUtil.show(this, "支付成功");
        sendBroadcast(BroadCastCode.REFRESH_PAY_CLINIC_LIST);
        PayClinicDetailActivity.launch(this, mOrderId);
        finish();
    }

    @Override
    public void onPayFail(String msg) {
        ToastUtil.show(this, "支付失败");
    }
}
